'use strict';

const Service = require('egg').Service;

class ReviewService extends Service {
  // 获取房源评价列表
  async list(propertyId, query = {}) {
    const { page = 1, pageSize = 10 } = query;
    const offset = (Number(page) - 1) * Number(pageSize);
    const limit = Number(pageSize);

    const sql = `
      SELECT r.*, u.username, u.avatar
      FROM property_reviews r
      LEFT JOIN users u ON r.user_id = u.id
      WHERE r.property_id = ? AND r.status = 'approved'
      ORDER BY r.created_at DESC
      LIMIT ? OFFSET ?
    `;

    const countSql = `
      SELECT COUNT(*) AS total
      FROM property_reviews
      WHERE property_id = ? AND status = 'approved'
    `;

    const [rows, countRows] = await Promise.all([
      this.app.mysql.query(sql, [propertyId, limit, offset]),
      this.app.mysql.query(countSql, [propertyId])
    ]);

    const total = countRows?.[0]?.total || 0;

    const items = rows.map(r => ({
      id: r.id,
      rating: r.rating,
      content: r.content,
      images: r.images ? JSON.parse(r.images) : [],
      created_at: r.created_at,
      user: {
        id: r.user_id,
        username: r.username,
        avatar: r.avatar
      }
    }));

    return { total, items };
  }

  // 获取房源评价统计
  async getStats(propertyId) {
    const sql = `
      SELECT 
        COUNT(*) as total_reviews,
        AVG(rating) as average_rating,
        SUM(CASE WHEN rating = 5 THEN 1 ELSE 0 END) as five_star,
        SUM(CASE WHEN rating = 4 THEN 1 ELSE 0 END) as four_star,
        SUM(CASE WHEN rating = 3 THEN 1 ELSE 0 END) as three_star,
        SUM(CASE WHEN rating = 2 THEN 1 ELSE 0 END) as two_star,
        SUM(CASE WHEN rating = 1 THEN 1 ELSE 0 END) as one_star
      FROM property_reviews
      WHERE property_id = ? AND status = 'approved'
    `;

    const rows = await this.app.mysql.query(sql, [propertyId]);
    const stats = rows[0] || {};

    return {
      total_reviews: Number(stats.total_reviews) || 0,
      average_rating: Number(stats.average_rating) || 0,
      rating_distribution: {
        5: Number(stats.five_star) || 0,
        4: Number(stats.four_star) || 0,
        3: Number(stats.three_star) || 0,
        2: Number(stats.two_star) || 0,
        1: Number(stats.one_star) || 0
      }
    };
  }

  // 创建评价
  async create(data) {
    const { property_id, user_id, rating, content, images } = data;

    // 检查是否已经评价过
    const existing = await this.app.mysql.get('property_reviews', {
      property_id,
      user_id
    });

    if (existing) {
      throw new Error('您已经评价过该房源');
    }

    const result = await this.app.mysql.insert('property_reviews', {
      property_id,
      user_id,
      rating,
      content,
      images: images ? JSON.stringify(images) : null,
      status: 'pending',
      created_at: new Date(),
      updated_at: new Date()
    });

    return result;
  }

  // 更新评价状态（管理员用）
  async updateStatus(id, status) {
    const result = await this.app.mysql.update('property_reviews', {
      status,
      updated_at: new Date()
    }, {
      where: { id }
    });

    return result;
  }
}

module.exports = ReviewService;
